package cui.xin.studentcourse.controller;

import cui.xin.studentcourse.dto.ResponseBean;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * <p>
 *  邮箱管理
 * </p>
 *
 * @author palpitate_yzr
 * @since 2022年11月16日16:35:55
 */
@RestController
@CrossOrigin //允许跨域访问
@Api(value = "邮箱管理")
@RequestMapping("/email")
public class EmailController {

    @Autowired
    JavaMailSender javaMailSender; //可直接注入邮件发送的对象

    @Value("${spring.mail.username}") //动态获取配置文件中 发送邮件的账户
    private String sendemail;

    @GetMapping("/getEmailCode")
    public ResponseBean getEmailCode(String email, HttpSession session){

        //随机生成一个四位数的验证码
        Integer yzm = new Random().nextInt(9999) % (9999 - 1000 + 1) + 1000;
        //创建简单邮件消息
        SimpleMailMessage message = new SimpleMailMessage();
        //谁发的
        message.setFrom(sendemail);
        //谁要接收
        message.setTo(email);
        //邮件标题
        message.setSubject("*✧⁺˚⁺ପ(๑･ω･)੭ु⁾⁾ 邮箱验证");
        Date date = new Date();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
        //邮件内容
        message.setText("─=≡Σ(((つ•̀ω•́)つ您的验证码是"+yzm+" ⊂(‘ω’⊂ )))Σ≡=─"+'\n'+"发送时间："+dateFormat.format(date));
        //把邮箱验证码传到session上
        session.setAttribute("emailYzm",yzm);
        javaMailSender.send(message);
        System.out.println(yzm);
        return new ResponseBean();
    }
}
